﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using CommonLib;
using Entities;
using Entities.System;
using BLL.System;
using BLL;
using BLL.Basic;
using BLL.Common;

namespace Haolaike
{
    public partial class _Default : System.Web.UI.Page
    {
        private bool IsAdmin
        {
            get
            {
                User user = (User)Session["user"];
                if (user.USER_ID == "Administrator") return true;
                else return false;
            }
        }

        public DataTable tblMenu = null;

        private void initTblMenu()
        {
            //缓存菜单表，编辑菜单时需要清除缓存
            if (tblMenu == null)
            {
                //取得DataTable 
                StringBuilder SqlTxt = new StringBuilder();
                User user = Session["user"] as User;
                MenuBO bo = new MenuBO();
                tblMenu = bo.getMyMenu(Convert.ToInt32(user.USER_KEY), IsAdmin);
                //  CacheHelper<DataTable>.Insert(new CacheKey(typeof(DataTable), "Menu"), tblMenu);
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            if (Session["user"] != null)
            {
                User user = (User)Session["user"];
                this.topUserName.InnerText = this.UserName.InnerText = user.USER_NAME;

                //Dictionary<string, string> dicEqual = new Dictionary<string, string>();
                //dicEqual.Add("UserID", user.UserID.ToString());

                GroupBO bo = new GroupBO();
                CustomerInfoBO boCustomer = new CustomerInfoBO();
                UserBO boUser = new UserBO();
                bool isAdmin = bo.isAdmin();
                CheckBoxBO cBo = new CheckBoxBO();
                List<CheckBox_List> CheckBoxItems = cBo.GetAllCheckItems();

                CacheData cache = new CacheData()
                {
                    User = user,
                    IsAdmin = isAdmin,
                    CheckBoxItems = CheckBoxItems

                };
                if (!isAdmin)
                {
                    //超级管理员不用读相关权限
                    cache.FActions = bo.getLoginerFunAction();

                }
                //读相关厂别
                cache.Factories = bo.getLoginerFactory();
                //cache.Customers = boCustomer.getAllCustomer(cache.Factories);
                cache.TEUser = boUser.getTEUser(user);

                Session["IndexCache"] = cache;
                var appPath = Request.ApplicationPath;
                if (appPath == "/") appPath = "";
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "appPath", string.Format("var appPath='{0}';", appPath), true);
                ScriptManager.RegisterStartupScript(this, this.GetType(), "cacheData", string.Format("var cacheData={0};", cache.ToJson()), true);
            }
        }

        private void registerMenuData()
        {
            List<MyMenu> menus = new List<MyMenu>();
            DataTable dt = tblMenu;

            if (dt != null && dt.Rows.Count > 0)
            {
                DataView dv = new DataView();
                dv.Table = dt;
                //根节点
                dv.RowFilter = "PARENT_KEY =0";
                dv.Sort = "SEQUENCE";
                if (dv.Count > 0)
                {
                    string RootFKey = dv[0]["FUNCTION_KEY"].ToString();
                    dv.RowFilter = "PARENT_KEY = '" + RootFKey + "'";

                    //定義DataRow承接DataTable篩選的結果 
                    if (dv.Count > 0)
                    {
                        for (int i = 0; i <= dv.Count - 1; i++)
                        {
                            DataRowView drv = dv[i];
                            MyMenu menu = new MyMenu();
                            menu.text = drv["FUNCTION_NAME"].ToString();
                            menu.type = Convert.ToInt32(drv["FUNC_TYPE"]);
                            menu.key = Convert.ToInt32(drv["FUNCTION_KEY"]);
                            menu.ToolTip = drv["FUNCTION_NAME"].ToString();
                            menu.subMenu = new List<MyMenu>();
                            //过滤子菜单
                            if (drv["FUNC_TYPE"].ToString() == "1") menu.href = String.Format("Page/{0}", drv["URL"].ToString());
                            menus.Add(menu);
                            AddSubMenu(menu, drv["FUNCTION_KEY"].ToString());
                        }
                    }
                }
            }
            ScriptManager.RegisterStartupScript(this, this.GetType(), "menu", string.Format("var menus={0};", menus.ToJson()), true);
        }

        protected void AddSubMenu(MyMenu pMenu, string PId)
        {
            DataTable dt = tblMenu;
            DataView dv = new DataView();
            dv.Table = dt;
            dv.RowFilter = "PARENT_KEY = '" + PId + "'";
            dv.Sort = "SEQUENCE";

            //如果篩選結果有資料 
            if (dv.Count > 0)
            {
                //逐筆取出篩選後資料 
                foreach (DataRowView drv in dv)
                {
                    MyMenu menu = new MyMenu();
                    menu.text = drv["FUNCTION_NAME"].ToString();
                    menu.type = Convert.ToInt32(drv["FUNC_TYPE"]);
                    menu.key = Convert.ToInt32(drv["FUNCTION_KEY"]);
                    menu.ToolTip = drv["FUNCTION_NAME"].ToString();
                    menu.subMenu = new List<MyMenu>();
                    //过滤子菜单
                    if (drv["FUNC_TYPE"].ToString() == "1") menu.href = drv["URL"].ToString();
                    pMenu.subMenu.Add(menu);
                    AddSubMenu(menu, drv["FUNCTION_KEY"].ToString());
                }
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (this.doLogout.Value == "1")
            {
                Session.Clear();
                Session.Abandon();
                Response.Redirect("Login.aspx?relogin=true");
            }
            if (!IsPostBack)
            {
                if (Session["user"] == null) Response.Redirect("Login.aspx");
                initTblMenu();
                registerMenuData();
            }
        }
    }
}
